package cn.mvc.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.fast.core.annotation.Parameter;
import org.fast.core.annotation.RequestMapping;
import org.fast.core.annotation.ResponseBody;
import org.fast.ioc.annotation.Controller;
import org.fast.ioc.annotation.Inject;
import org.fast.web.render.Renderer;
import org.fast.web.render.TemplateRenderer;
import org.fast.web.render.TextRenderer;

import cn.mvc.exception.ServiceException;
import cn.mvc.model.Category;
import cn.mvc.model.Json;
import cn.mvc.web.service.CategoryService;

@Controller
@RequestMapping("/cate")
public class CategoryController {

	@Inject
	private CategoryService cateService;

	@Parameter
	private Category cate;

	@RequestMapping("/add")
	@ResponseBody
	public Json add() {
		Json json = new Json();
		try {
			int r = cateService.addCategory(cate);
			json.setSuccess(r > 0);
			json.setMsg(r > 0 ? "添加分类成功" : "添加分类失败");
		} catch (ServiceException e) {
			json.setMsg(e.getMessage());
		}
		return json;
	}

	@RequestMapping("/del/{id}")
	@ResponseBody
	public Json del(int id) {
		Json json = new Json();
		try {
			int r = cateService.delCategory(id);
			json.setSuccess(r > 0);
			json.setMsg(r > 0 ? "删除成功" : "分类不存在或已删除");
		} catch (ServiceException e) {
			json.setMsg(e.getMessage());
		}
		return json;
	}

	@RequestMapping("/list")
	public Renderer list() {
		List<Category> list = new ArrayList<Category>();
		try {
			list = cateService.queryCategories();
			return new TemplateRenderer("/category.jsp", "catelist", list);
		} catch (ServiceException e) {
			return new TextRenderer(e.getMessage());
		}
	}

	public CategoryService getCateService() {
		return cateService;
	}

	public void setCateService(CategoryService cateService) {
		this.cateService = cateService;
	}

	public Category getCate() {
		return cate;
	}

	public void setCate(Category cate) {
		this.cate = cate;
	}

}
